//
//  WCNewProjectFromFolderSheetController.m
//  WabbitCode
//
//  Created by William Towe on 2/12/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCNewProjectFromFolderSheetController.h"
#import "WCNewProjectWindowController.h"
#import "NSResponder+WCExtensions.h"
#import "WCMacros.h"
#import "EncodingManager.h"
#import "WCAppController.h"
#import "WCBuildTarget.h"
#import "NSDictionary+WCExtensions.h"


static NSDictionary *_newProjectModelsDictionary = nil;

@implementation WCNewProjectFromFolderSheetController
#pragma mark *** Subclass Overrides ***
+ (void)initialize {
	_newProjectModelsDictionary = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NewProjectModels" ofType:@"plist"]];
}

- (id)init {
	if (!(self = [self initWithWindowNibName:@"WCNewProjectFromFolderSheet"]))
		return nil;
	
	_projectFolderPath = [NSHomeDirectory() copy];
	
	return self;
}

- (void)dealloc {
	[_projectFolderPath release];
	[_mainAssemblyFilePath release];
	[super dealloc];
}

- (void)windowDidLoad {
	[super windowDidLoad];
	
	for (NSDictionary *mDict in [_newProjectModelsDictionary objectForKey:@"models"]) {
		NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:[mDict objectForKey:@"name"] action:[_targetModelPopUpButton action] keyEquivalent:@""] autorelease];
		[item setTag:[mDict unsignedIntegerForKey:@"model"]];
		[[_targetModelPopUpButton menu] addItem:item];
	}
	
	for (NSDictionary *oDict in [[[_newProjectModelsDictionary objectForKey:@"models"] objectAtIndex:0] objectForKey:@"outputs"]) {
		NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:[oDict objectForKey:@"name"] action:[_targetOutputTypePopUpButton action] keyEquivalent:@""] autorelease];
		[item setTag:[oDict unsignedIntegerForKey:@"output"]];
		[[_targetOutputTypePopUpButton menu] addItem:item];
	}
	
	[_encodingPopUpButton setEncoding:NoStringEncoding defaultEntry:YES];
	
	[_targetModelPopUpButton selectItemWithTag:NSUserDefaultsIntegerForKey(kWCNewProjectFromFolderTargetModelKey)];
	[self targetModelPopUpButtonAction:_targetModelPopUpButton];
	[_targetOutputTypePopUpButton selectItemWithTag:NSUserDefaultsIntegerForKey(kWCNewProjectFromFolderTargetOutputTypeKey)];
	[self setProjectFolderPath:NSUserDefaultsObjectForKey(kWCNewProjectFromFolderRootFolderKey)];
}

#pragma mark *** Public Methods ***
+ (void)presentNewProjectFromFolderSheet; {
	WCNewProjectFromFolderSheetController *controller = [[[self class] alloc] init];
	
	[NSApp beginSheet:[controller window] modalForWindow:[NSApp keyWindow] modalDelegate:controller didEndSelector:@selector(_sheetDidEnd:code:info:) contextInfo:NULL];
}
#pragma mark Accessors
@synthesize projectFolderPath=_projectFolderPath,mainAssemblyFilePath=_mainAssemblyFilePath;

#pragma mark IBActions
- (IBAction)chooseProjectFolderPathAction:(id)sender; {
	NSOpenPanel *panel = [NSOpenPanel openPanel];
	
	[panel setCanChooseFiles:NO];
	[panel setCanChooseDirectories:YES];
	[panel setPrompt:NSLocalizedString(@"Choose",@"Choose")];
	[panel setTitle:NSLocalizedString(@"Select Project Folder",@"Select Project Folder")];
	
	if ([panel runModalForDirectory:[self projectFolderPath] file:nil] != NSOKButton)
		return;
	
	[self setProjectFolderPath:[panel directory]];
}

- (IBAction)targetModelPopUpButtonAction:(id)sender; {
	[_targetOutputTypePopUpButton removeAllItems];
	
	for (NSDictionary *oDict in [[[_newProjectModelsDictionary objectForKey:@"models"] objectAtIndex:[_targetModelPopUpButton indexOfSelectedItem]] objectForKey:@"outputs"]) {
		NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:[oDict objectForKey:@"name"] action:[_targetOutputTypePopUpButton action] keyEquivalent:@""] autorelease];
		[item setTag:[oDict unsignedIntegerForKey:@"output"]];
		[[_targetOutputTypePopUpButton menu] addItem:item];
	}
}

- (IBAction)chooseMainAssemblyFileAction:(id)sender; {
	NSOpenPanel *panel = [NSOpenPanel openPanel];
	
	[panel setPrompt:NSLocalizedString(@"Choose",@"Choose")];
	[panel setTitle:NSLocalizedString(@"Select Main Assembly File",@"Select Main Assembly File")];
	
	if ([panel runModalForDirectory:[self projectFolderPath] file:nil types:[NSArray arrayWithObject:kWCAssemblyUTI]] != NSOKButton)
		return;
	
	[self setMainAssemblyFilePath:[[panel filenames] objectAtIndex:0]];
}
#pragma mark *** Private Methods ***
- (void)_sheetDidEnd:(NSWindow *)window code:(NSInteger)code info:(void *)info {
	[self autorelease];
	if (code != NSOKButton)
		return;
	
	NSStringEncoding encoding = ([_encodingPopUpButton selectedTag] == NoStringEncoding)?kWCDefaultFileEncoding:[_encodingPopUpButton selectedTag];
	NSError *error = nil;
	if (![[WCNewProjectWindowController sharedInstance] createNewProjectAtPath:[self projectFolderPath] forTargetModel:[_targetModelPopUpButton selectedTag] targetOutputType:[_targetOutputTypePopUpButton selectedTag] mainAssemblyFilePath:[self mainAssemblyFilePath] usingEncoding:encoding error:&error]) {
		// TODO: display the error
		[self presentError:error];
		return;
	}
	
	// update the preferences
	NSSetUserDefaultsObjectForKey([self projectFolderPath], kWCNewProjectFromFolderRootFolderKey);
	NSSetUserDefaultsUnsignedIntegerForKey([_targetModelPopUpButton selectedTag], kWCNewProjectFromFolderTargetModelKey);
	NSSetUserDefaultsUnsignedIntegerForKey([_targetOutputTypePopUpButton selectedTag], kWCNewProjectFromFolderTargetOutputTypeKey);
	
	[[WCNewProjectWindowController sharedInstance] dismissModalWindowAction:nil];
}
@end
